package com.lwj.project1.PersonActivity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.lwj.project1.MainActivity;
import com.lwj.project1.R;
import com.lwj.project1.databaseHelper.ImageUtil;
import com.lwj.project1.databaseHelper.MySqliteOpenHelper;
import com.lwj.project1.entity.User;
import com.lwj.project1.myToast.MyToast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class EditPersonInfoActivity extends AppCompatActivity {

    private ImageButton editHead;
    private EditText editPhone;
    private EditText editEmail;
    private EditText editSex;
    private EditText editLocation;
    private EditText editDescription;
    private Button update;
    private MyToast myToast;
    private String headStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_person_info);
        editHead = findViewById(R.id.edit_head);
        editPhone = findViewById(R.id.edit_phone);
        editEmail = findViewById(R.id.edit_email);
        editSex = findViewById(R.id.edit_sex);
        editLocation = findViewById(R.id.edit_location);
        editDescription = findViewById(R.id.edit_description);
        update = findViewById(R.id.button9);
        MySqliteOpenHelper mySqliteOpenHelper = new MySqliteOpenHelper(getApplicationContext());
        SharedPreferences sharedPreferences = getSharedPreferences("project_content",MODE_PRIVATE);
        myToast = new MyToast(getApplicationContext());
        // TODO 然后实现 桌游详情页的展示 再看看聊天 与联系人展示的实现 然后编写文档

        User user = mySqliteOpenHelper.findUserByName(sharedPreferences.getString("username",""));
        User updateUser = new User();
        if (updateUser == null) Toast.makeText(this, "wrong", Toast.LENGTH_SHORT).show();
        if (user == null) return;
        if (user.getHeadImgStr() != null)editHead.setImageBitmap(ImageUtil.base64ToImage(user.getHeadImgStr()));
        editPhone.setText(user.getPhone());
        editEmail.setText(user.getEmail());
        editSex.setText(user.getGender());
        editLocation.setText(sharedPreferences.getString("location",""));
        editDescription.setText(user.getDescription());
        editHead.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(EditPersonInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                getFromAlbum();
            }else{
                ActivityCompat.requestPermissions(EditPersonInfoActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);
            }
        });
        update.setOnClickListener(v -> {
            if (updateUser == null) {
                Toast.makeText(this, "wrong", Toast.LENGTH_SHORT).show();
                return;
            }
            String phone = editPhone.getText().toString();
            Log.i("phone",phone);
            String email = editEmail.getText().toString();
            String sex = editSex.getText().toString();
            String location = editLocation.getText().toString();
            String description = editDescription.getText().toString();
            if (phone.equals("") || email.equals("") || sex.equals("")) {
                myToast.showToastWithImg("填的信息不能为空哦~",getResources().getDrawable(R.drawable.toast_img));
                return;
            }
            updateUser.setUserName(sharedPreferences.getString("username",""));
            if (headStr != null){
                updateUser.setHeadImgStr(headStr);
            }
            updateUser.setPhone(phone);
            updateUser.setEmail(email);
            updateUser.setGender(sex);
            updateUser.setDescription(description);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("location",location);
            editor.apply();
            if (mySqliteOpenHelper.updateUser(updateUser)){
                myToast.showToastWithImg("修改信息成功啦~",getResources().getDrawable(R.drawable.toast_img));
                Intent intent = new Intent(EditPersonInfoActivity.this, MainActivity.class);
                startActivity(intent);
            }
            else myToast.showToastWithImg("修改信息失败！",getResources().getDrawable(R.drawable.toast_img));
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1){
            handleImage(data);
        }
    }

    private String getImagePath(Uri uri, String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor != null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void handleImage(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(EditPersonInfoActivity.this,uri)){
            String documentId = DocumentsContract.getDocumentId(uri);
            if (TextUtils.equals(uri.getAuthority(),"com.android.providers.media.documents")){
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if (TextUtils.equals(uri.getAuthority(),"com.android.providers.downloads.documents")){
                if (documentId != null && documentId.startsWith("msf:")){
                    resolveMSF(uri,documentId);
                    return;
                }
                Uri contentUri =  ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.parseLong(documentId));
                imagePath = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            imagePath = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            editHead.setImageBitmap(bitmap);
            headStr = ImageUtil.imageToBase64(bitmap);
        }
    }

    private void resolveMSF(Uri uri, String documentId) {
        File file = new File(getCacheDir(),"temp_file" + getContentResolver().getType(uri).split("/")[1]);
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);

            OutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[4*1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,read);
            }
            outputStream.flush();

            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            editHead.setImageBitmap(bitmap);
            headStr = ImageUtil.imageToBase64(bitmap);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                getFromAlbum();
            }else{
                myToast.showToastWithImg("访问相册权限被拒绝~",getDrawable(R.drawable.toast_img));
            }
        }

    }
    private void getFromAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,1);
    }
}